package GUILag;

import ControllerLag.WorkingPlanCTR;
import ModelLag.Employee;
import ModelLag.Shift;
import ModelLag.WorkingPlan;
import java.awt.Dimension;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import javax.swing.JFormattedTextField;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

/**
 * Panel som bruges til vagtplan for hver afdeling.
 * @author DM75 Gruppe 3
 * @version 2011-12-22
 */
public class WPPanel extends javax.swing.JPanel {
    private GregorianCalendar date;
    private WorkingPlanCTR WPCTR;
    private String loc;
    private String userLevel;
    private WorkingPlanGUI WPGUI;
    private ArrayList<WorkingPlan> workingPlans;
    /** Creates new form WPReceptionPanel */
public WPPanel() {
        initComponents();
    }

    public WPPanel(String loc, String userLevel, WorkingPlanGUI WPGUI) {
        initComponents();
        this.userLevel = userLevel;
        this.loc = loc;
        this.WPGUI = WPGUI;
        WPCTR = new WorkingPlanCTR();
        date = new GregorianCalendar();
        setDateField();
        workingPlans = new ArrayList<WorkingPlan>();
        wpTable.getColumnModel().getColumn(0).setPreferredWidth(60);
        wpTable.getColumnModel().getColumn(1).setPreferredWidth(80);
        wpTable.getColumnModel().getColumn(2).setPreferredWidth(40);
        wpTable.getColumnModel().getColumn(3).setPreferredWidth(40);
        wpTable.getColumnModel().getColumn(4).setPreferredWidth(40);
        updateTable();

        // Gør sådan at man kan højreklikke i tabellen.
        wpTable.addMouseListener( new MouseAdapter()
        {
        public void mouseReleased(MouseEvent e)
        {
            if (e.isPopupTrigger())
            {
                JTable source = (JTable)e.getSource();
                int row = source.rowAtPoint( e.getPoint() );
                int column = source.columnAtPoint( e.getPoint() );

                if (! source.isRowSelected(row))
                    source.changeSelection(row, column, false, false);
                
                if(wpTable.getValueAt(source.getSelectedRow(), 3) == null)
                {
                    updTimeMenuItem.setEnabled(false);
                    deleteMenuItem.setEnabled(false);
                    updEmpMenuItem.setEnabled(false);
                }
                else
                {
                    updEmpMenuItem.setEnabled(true);
                    if(!getUserLevel().equals("Administrator"))
                    {
                        updTimeMenuItem.setEnabled(false);
                        deleteMenuItem.setEnabled(false);
                    }
                    else
                    {
                        updTimeMenuItem.setEnabled(true);
                        deleteMenuItem.setEnabled(true);
                    }                     
                }
                jPopupMenu1.show(e.getComponent(), e.getX(), e.getY());
            }
        }
        });
        
    }
    
    private String getUserLevel()
    {
        return userLevel;
    }
    
    protected int getSelectedRow()
    {
        return wpTable.getSelectedRow();
    }
    
    protected String getLoc()
    {
        return loc;
    }
    
    // Henter modellen på tabellen som bruges til at slette/tilføje/redigerer indholdet i tabellen.
    protected DefaultTableModel getModel()
    {
        return (DefaultTableModel) wpTable.getModel();
    }
    
    // Gør det muligt at printe tabellen.
    private void printTable()
    {
        try
        {
            MessageFormat mF = new MessageFormat("Vagtplan for " + getLoc() + " " + dateLabel.getText());
            
            Date printDate = new Date();
            MessageFormat mF2 = new MessageFormat(String.format("Printet: %1$tA den %1$te. %1$tB %1$tY kl. %1$tT\n", printDate));
            
            wpTable.print(JTable.PrintMode.NORMAL, mF, mF2);
        }
        catch(Exception e)
        {
            System.out.println(e.getMessage());
        }
    }
    
    
    // Opdatere tabellen.
    private void updateTable()
    {
        addWeekDayAndDateToTable(dateLabel.getText(), getLoc());
    }
    
    // Tilføjer rækker i tabellen med ugedag og dato, samt evt vagter.
    private void addWeekDayAndDateToTable(String monthYear, String location)
    {
        int month = Integer.parseInt(monthYear.substring(0, 2));
        int year = Integer.parseInt(monthYear.substring(3, 7));
        
        workingPlans = WPCTR.getWorkingPlansMonthLoc(month, year, location, true);
        
        Date datesThisMonth[] = getDatesThisMonth(month, year);
        
        String weekDay = "";
        Date newDate = null;
        GregorianCalendar date = new GregorianCalendar();
        
        int index = 0;
        while(index < datesThisMonth.length)
        {
            newDate = datesThisMonth[index];
            date.setTime(newDate);
            weekDay = getWeekDay(date.get(date.DAY_OF_WEEK));
   
            Object[] data = {weekDay, newDate};
            
            getModel().addRow(data);
// Lavede et kald ned til databasen for hver dato og lokalitet. Mange kald til databasen. 120 ialt pt. Derfor bruges den anden metode.
//            addShiftsIntoTable(date, location); 
            
// Laver et kald til databasen for måned og lokalitet. 4 ialt pt.
            addShifts(date);  
            index++;
        }        
    }
    
    /**
     * Tilføjer de vagter der er for den specifikke dato.
     * @param date 
     */
    private void addShifts(GregorianCalendar date)
    {
        boolean found = false;
        int index = 0;
        while(index < workingPlans.size() && !found)
        {
            if(workingPlans.get(index).getDate().equals(date))
            {
                found = true;
            }
            else
            {
                index++;
            }
        }
        if(found)
        {
            WorkingPlan workingPObj = workingPlans.get(index);
                String startTime = "";
                String endTime = "";
                String name = "";
                String hours = "";
                String cprNo = "";

                for(Shift shiftObj : workingPObj.getShifts())
                {
                    startTime = shiftObj.getStartTime().substring(0, 5);
                    endTime = shiftObj.getEndTime().substring(0, 5);
                    name = shiftObj.getEmployee().getfName() + " " + shiftObj.getEmployee().getlName();
                    hours = "" + shiftObj.getHours();
                    cprNo = shiftObj.getEmployee().getCprNo();

                    Object[] data = {null, null, startTime, endTime, hours, name, cprNo};

                    getModel().addRow(data);
                }
                workingPlans.remove(index);
        }
    }
    
    // henter ugedag.
    private String getWeekDay(int weekDayNumb)
    {
        String weekday = "";
        switch(weekDayNumb)
        {
            case 1:
                weekday = "Søndag";
                break;
                
            case 2:
                weekday = "Mandag";
                break;
                
            case 3:
                weekday = "Tirsdag";
                break;
                
            case 4:
                weekday = "Onsdag";
                break;
                
            case 5:
                weekday = "Torsdag";
                break;
                
            case 6:
                weekday = "Fredag";
                break;
                
            case 7:
                weekday = "Lørdag";
                break;
        }

        return weekday;
    }
    
    
    private void setDateField()
    {
        dateLabel.setText(getInitialMonthYear());
    }
    
    // Henter alle datoer som er i den måned og år som er angivet i parameteren.
    private Date[] getDatesThisMonth(int month, int year)
    {
        int firstDayInMonth = 1;
        
        GregorianCalendar firstDateInMonth = new GregorianCalendar(year, month-1, firstDayInMonth);
        
        int lastDayInMonth = firstDateInMonth.getActualMaximum(firstDateInMonth.DAY_OF_MONTH);
        Date[] datesInThisMonth = new Date[lastDayInMonth];
        
        while(firstDayInMonth <= lastDayInMonth)
        {
            Date newDate = firstDateInMonth.getTime();
            datesInThisMonth[firstDayInMonth -1] = newDate;
            firstDateInMonth.add(firstDateInMonth.DAY_OF_MONTH, 1);
            firstDayInMonth++;
        }

        return datesInThisMonth;
    }
    
    /**
     * Henter den måned som der når programmet starter op.
     * @return 
     */
    private String getInitialMonthYear()
    {
        int month = date.get(date.MONTH)+1;
        String monthS = "";
        if(month < 10)
        {
            monthS = "0" + month;
        }
        else
        {
            monthS = "" + month;
        }
            
        String yearS = "" + (date.get(date.YEAR));   
        return monthS + "-" + yearS;
    }
    
    /**
     * Sætter næste måned.
     */
    private void setNextMonthYear()
    {
        date.add(date.MONTH, 1);
        setDateField();
    }
    
    /**
     * Sætter forrige måned.
     */
    private void setPreviousMonthYear()
    {
        date.add(date.MONTH, -1);
        setDateField();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPopupMenu1 = new javax.swing.JPopupMenu();
        updTimeMenuItem = new javax.swing.JMenuItem();
        updEmpMenuItem = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JPopupMenu.Separator();
        deleteMenuItem = new javax.swing.JMenuItem();
        jPanel2 = new javax.swing.JPanel();
        previousMonthButton = new javax.swing.JButton();
        dateLabel = new javax.swing.JLabel();
        nextMonthButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        wpTable = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        printButton = new javax.swing.JButton();

        updTimeMenuItem.setText("Ændre arbejdstid");
        updTimeMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                updTimeMenuItemActionPerformed(evt);
            }
        });
        jPopupMenu1.add(updTimeMenuItem);

        updEmpMenuItem.setText("Ændre medarbejder");
        updEmpMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                updEmpMenuItemActionPerformed(evt);
            }
        });
        jPopupMenu1.add(updEmpMenuItem);
        jPopupMenu1.add(jSeparator1);

        deleteMenuItem.setText("Slet vagt");
        deleteMenuItem.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                deleteMenuItemMouseClicked(evt);
            }
        });
        deleteMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteMenuItemActionPerformed(evt);
            }
        });
        jPopupMenu1.add(deleteMenuItem);

        previousMonthButton.setText("<<");
        previousMonthButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                previousMonthButtonActionPerformed(evt);
            }
        });

        dateLabel.setFont(new java.awt.Font("Tahoma", 1, 14));
        dateLabel.setText("Måned-År");

        nextMonthButton.setText(">>");
        nextMonthButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                nextMonthButtonActionPerformed(evt);
            }
        });

        wpTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Ugedag", "Dato", "Start", "Slut", "Timer", "Medarbejder", "CprNummer"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.util.Date.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        wpTable.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        wpTable.getTableHeader().setReorderingAllowed(false);
        wpTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                wpTableMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(wpTable);
        wpTable.removeColumn(wpTable.getColumnModel().getColumn(6));

        jButton1.setText("Luk");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        printButton.setText("Print");
        printButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                printButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(106, 106, 106)
                        .addComponent(previousMonthButton)
                        .addGap(18, 18, 18)
                        .addComponent(dateLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(nextMonthButton))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 397, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                                .addComponent(printButton)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jButton1)))))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(dateLabel)
                    .addComponent(previousMonthButton)
                    .addComponent(nextMonthButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 587, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(printButton))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
    }// </editor-fold>//GEN-END:initComponents

    private void deleteMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteMenuItemActionPerformed
        int selectedRow = wpTable.getSelectedRow();
        // Bruges for at sikre at det er en oprettet vagt man trykker på og ikke en dato og ugedag.
        if(wpTable.getValueAt(selectedRow, 5) != null)
        {
        
        int input = JOptionPane.showConfirmDialog(this, "Er du sikker på du vil slette?", "Bekræft sletning", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);
            
            if(input == JOptionPane.OK_OPTION)
            {
                int index = selectedRow;
                // Bruges til at finde datoen for den markerede vagt.
                while(wpTable.getValueAt(index, 1) == null)
                {
                    index--;
                }

                GregorianCalendar newDate = new GregorianCalendar();
                newDate.setTime((Date)wpTable.getValueAt(index, 1));

                String location = getLoc();
                String cprNo = (String) getModel().getValueAt(selectedRow, 6);
                String startTime = (String) wpTable.getValueAt(selectedRow, 2);
                String endTime = (String) wpTable.getValueAt(selectedRow, 3);

                int result = WPCTR.deleteShift(newDate, location, cprNo, startTime, endTime);
                if(result == 1)
                {
                    JOptionPane.showMessageDialog(this, "Sletning er fuldført.", "Sletning lykkedes", JOptionPane.INFORMATION_MESSAGE);
                    getModel().removeRow(wpTable.convertRowIndexToModel(selectedRow));
                }
            } 
        }
        else
        {
            JOptionPane.showMessageDialog(this, "Du skal vælge en vagt.", "Hvad vil du?", JOptionPane.INFORMATION_MESSAGE);
        }
    }//GEN-LAST:event_deleteMenuItemActionPerformed

    private void previousMonthButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_previousMonthButtonActionPerformed
        setPreviousMonthYear();
        getModel().setRowCount(0);
        updateTable();
    }//GEN-LAST:event_previousMonthButtonActionPerformed

    private void nextMonthButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nextMonthButtonActionPerformed
        setNextMonthYear();
        getModel().setRowCount(0);
        updateTable();
    }//GEN-LAST:event_nextMonthButtonActionPerformed

    // Henter den dato som er markeret i tabellen.
    protected Date getDateInTable()
    {
        int selectedRow = wpTable.getSelectedRow();
        return (java.util.Date) wpTable.getValueAt(selectedRow, 1);
    }
    // Henter den ugedag som er markeret i tabellen.
    protected String getWeekDay()
    {
        int selectedRow = wpTable.getSelectedRow();
        return (String) wpTable.getValueAt(selectedRow, 0);
    }
    
    private void updTimeMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_updTimeMenuItemActionPerformed
        int selectedRow = wpTable.getSelectedRow();
        // Bruges for at sikre at det er en oprettet vagt man trykker på og ikke en dato og ugedag.
        if(wpTable.getValueAt(selectedRow, 5) != null)
        {
            JFormattedTextField endFormatTF = new javax.swing.JFormattedTextField();
            endFormatTF.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.DateFormatter(java.text.DateFormat.getTimeInstance(java.text.DateFormat.SHORT))));

            JFormattedTextField startFormatTF = new javax.swing.JFormattedTextField();
            startFormatTF.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.DateFormatter(java.text.DateFormat.getTimeInstance(java.text.DateFormat.SHORT))));

            // Strings og JTexFields som skal vises i JOptionpane.
            Object[] message = new Object[] {"Ny start(TT:MM):", startFormatTF, "Ny slut(TT:MM):", endFormatTF};  
            // Knapper på JOptionpane.
            Object[] options = {"OK", "Annuller"};
            // Bruges for at få fokus i det første textfield i JOptionpanet.
            int input = JOptionPane.showOptionDialog(this, message, "Ændring af arbejdstid på vagt", JOptionPane.OK_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options, "");

            if(input == JOptionPane.OK_OPTION)
            {
                if(startFormatTF.getText().length() == 5 && endFormatTF.getText().length() == 5)
                {
                    int startTimeMin = (Integer.parseInt(startFormatTF.getText().substring(0,2)))*60 + Integer.parseInt(startFormatTF.getText().substring(3,5));
                    int endTimeMin = (Integer.parseInt(endFormatTF.getText().substring(0,2)))*60 + Integer.parseInt(endFormatTF.getText().substring(3,5));
            
                    if(startTimeMin > endTimeMin)
                    {
                        JOptionPane.showMessageDialog(this, "Starttidspunkt skal være før Sluttidspunkt.\nEn vagt kan senest slutte 23:59.", "Tidsrum", JOptionPane.ERROR_MESSAGE);
                        // metode kalder sig selv igen.
                        updTimeMenuItemActionPerformed(evt);
                    }
                    else
                    {
                        int index = selectedRow;
                        // Bruges til at finde datoen for den markerede vagt.
                        while(wpTable.getValueAt(index, 1) == null)
                        {
                            index--;
                        }
                        GregorianCalendar newDate = new GregorianCalendar();
                        newDate.setTime((Date)wpTable.getValueAt(index, 1));

                        String location = getLoc();
                        String cprNo = (String) getModel().getValueAt(selectedRow, 6);
                        String startTime = (String) wpTable.getValueAt(selectedRow, 2);
                        String endTime = (String) wpTable.getValueAt(selectedRow, 3);

                        int result = WPCTR.updateShift(newDate, location, cprNo, startTime, endTime, cprNo, startFormatTF.getText(), endFormatTF.getText());
                        if(result == 1)
                        {
                            double hours = WPCTR.getHoursFromStartToEnd(startFormatTF.getText(), endFormatTF.getText());
                            // sætter på modellen.
                            getModel().setValueAt(startFormatTF.getText(), selectedRow, 2);
                            getModel().setValueAt(endFormatTF.getText(), selectedRow, 3);
                            getModel().setValueAt(hours, selectedRow, 4);
                            JOptionPane.showMessageDialog(this, "Opdatering er fuldført.", "Opdatering lykkedes", JOptionPane.INFORMATION_MESSAGE);
                        }
                        else
                        {
                            JOptionPane.showMessageDialog(this, "En fejl er opstået.", "Opdatering mislykkedes", JOptionPane.ERROR_MESSAGE);
                        }
                    }       
                }
                else
                {
                    JOptionPane.showMessageDialog(this, "Indtast gyldige tidspunkter. (TT:MM)", "Opdatering mislykkedes", JOptionPane.ERROR_MESSAGE);
                }
            }
        }
        else
        {
            JOptionPane.showMessageDialog(this, "Du skal vælge en vagt.", "Hvad vil du?", JOptionPane.INFORMATION_MESSAGE);
        }
    }
        // TODO add your handling code here:}//GEN-LAST:event_updTimeMenuItemActionPerformed

    private void deleteMenuItemMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_deleteMenuItemMouseClicked
        
    }//GEN-LAST:event_deleteMenuItemMouseClicked

    public void setWorkingPlanGUIDisabled()
    {
        WPGUI.setWorkingPlanGUIDisabled();
    }
    
    public void setWorkingPlanGUIEnabled()
    {
        WPGUI.setWorkingPlanGUIEnabled();
    }
    
    private void wpTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_wpTableMouseClicked
            int selectedRow = wpTable.getSelectedRow();
            Date dateInTable =(java.util.Date) wpTable.getValueAt(selectedRow, 1);

            if(evt.getClickCount() == 2 && dateInTable != null)
            {
                if(userLevel.equals("Administrator"))
                {       
                    CreateShiftGUI createShiftGUI = new CreateShiftGUI(this);
                    createShiftGUI.setLocation(500, 300);
                    createShiftGUI.setVisible(true);
                }
                else
                {
                    JOptionPane.showMessageDialog(this, "Du har ikke adgang til at tilføje nye vagter.", "Adgang nægtet", JOptionPane.INFORMATION_MESSAGE);
                }
            }
            else if (evt.getClickCount() == 2 && dateInTable == null)
            {
                JOptionPane.showMessageDialog(this, "Dobbeltklik på en dato for at tilføje en vagt. Højre klik hvis du vil redigere eller slette vagten.", "Hvad vil du?", JOptionPane.INFORMATION_MESSAGE);
            }
        
    }//GEN-LAST:event_wpTableMouseClicked

    private void updEmpMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_updEmpMenuItemActionPerformed
        int selectedRow = wpTable.getSelectedRow();
        // Bruges for at sikre at det er en oprettet vagt man trykker på og ikke en dato og ugedag.
        if(wpTable.getValueAt(selectedRow, 5) != null)
        {
            String startTime = (String)wpTable.getValueAt(selectedRow, 2);
            String endTime = (String)wpTable.getValueAt(selectedRow, 3);
            String empName = (String)wpTable.getValueAt(selectedRow, 5);
            String oldCprNo = (String) getModel().getValueAt(selectedRow, 6);
            String location = getLoc();

            int index = selectedRow;
            // Bruges til at finde datoen for den markerede vagt.
            while(wpTable.getValueAt(index, 1) == null)
            {
                index--;
            }

            GregorianCalendar newDate = new GregorianCalendar();
            newDate.setTime((Date)wpTable.getValueAt(index, 1));


            int index2 = 0;
            Employee[] empAvail = new Employee[WPCTR.getEmployeesAvailableForThisShift(newDate, startTime, endTime).size()];

            for(Employee employeeObj : WPCTR.getEmployeesAvailableForThisShift(newDate, startTime, endTime))
                {
                    empAvail[index2] = employeeObj;
                    index2++;
                }
            // Scroll på listen.
            JList<Employee> list = new JList<Employee>(empAvail);
            JScrollPane scroller = new JScrollPane(list);
            
            scroller.setPreferredSize(new Dimension (50, 100));
            scroller.getViewport().add(list);
            

            Object[] message = new Object[] {"Starttid: " + startTime, "Sluttid: " + endTime, "Nuværende medarbejder: " + empName, "Tilgængelige medarbejdere: ", scroller};  
            // Knapper på JOptionpane.
            Object[] options = {"OK", "Annuller"};
            // Bruges for at få fokus i det første textfield i JOptionpanet.
            int input = JOptionPane.showOptionDialog(this, message, "Ændre medarbejder på vagt", JOptionPane.OK_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options, "");
            if(input == JOptionPane.OK_OPTION)
            {
                if(list.getSelectedValue() != null)
                {
                    String cprNo = list.getSelectedValue().getCprNo();
                    int result = WPCTR.updateShift(newDate, location, oldCprNo, startTime, endTime, cprNo, startTime, endTime);
                    if(result == 1)
                    {
                        String name = list.getSelectedValue().getfName() + " " + list.getSelectedValue().getlName();
                        getModel().setValueAt(name, selectedRow, 5);
                        getModel().setValueAt(cprNo, selectedRow, 6);
                        JOptionPane.showMessageDialog(this, "Opdatering er fuldført.", "Opdatering lykkedes", JOptionPane.INFORMATION_MESSAGE);
                    }
                    else
                    {
                        JOptionPane.showMessageDialog(this, "En fejl er opstået.", "Opdatering mislykkedes", JOptionPane.ERROR_MESSAGE);
                    }
                }
                else
                {
                    JOptionPane.showMessageDialog(this, "Du skal vælge en medarbejder i listen!", "Opdatering mislykkedes", JOptionPane.ERROR_MESSAGE);
                    //Kalder sig selv.
                    updEmpMenuItemActionPerformed(evt);
                }
            }
        }
        else
        {
            JOptionPane.showMessageDialog(this, "Du skal vælge en vagt.", "Hvad vil du?", JOptionPane.INFORMATION_MESSAGE);
        }
    }//GEN-LAST:event_updEmpMenuItemActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        WPGUI.closeFrame();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void printButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_printButtonActionPerformed
        printTable();
    }//GEN-LAST:event_printButtonActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel dateLabel;
    private javax.swing.JMenuItem deleteMenuItem;
    private javax.swing.JButton jButton1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPopupMenu jPopupMenu1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JPopupMenu.Separator jSeparator1;
    private javax.swing.JButton nextMonthButton;
    private javax.swing.JButton previousMonthButton;
    private javax.swing.JButton printButton;
    private javax.swing.JMenuItem updEmpMenuItem;
    private javax.swing.JMenuItem updTimeMenuItem;
    private javax.swing.JTable wpTable;
    // End of variables declaration//GEN-END:variables


}
